<template>
  <div class="dashboard-container" :class="{ 'dark-mode': darkMode }">
    <!-- 工具栏 -->
    <div class="toolbar">
      <el-button 
        type="primary" 
        :icon="Refresh"
        :loading="refreshing"
        @click="handleRefresh"
      >
        刷新数据
      </el-button>
      <el-switch
        v-model="darkMode"
        class="theme-switch"
        inline-prompt
        :active-icon="Moon"
        :inactive-icon="Sunny"
        @change="handleThemeChange"
      />
    </div>

    <!-- 数据卡片 -->
    <el-row :gutter="20" v-loading="loading.statistics">
      <el-col :span="6">
        <el-card class="data-card">
          <div class="card-header">
            <div class="title">今日订单数</div>
            <el-icon class="icon"><ShoppingCart /></el-icon>
          </div>
          <div class="number">{{ statistics.todayOrderCount }}</div>
          <div class="compare">
            较昨日
            <span :class="statistics.orderIncrease >= 0 ? 'up' : 'down'">
              {{ Math.abs(statistics.orderIncrease) }}%
              <el-icon>
                <component :is="statistics.orderIncrease >= 0 ? 'CaretTop' : 'CaretBottom'" />
              </el-icon>
            </span>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="data-card">
          <div class="card-header">
            <div class="title">今日销售额</div>
            <el-icon class="icon"><Money /></el-icon>
          </div>
          <div class="number">¥{{ statistics.todaySales.toFixed(2) }}</div>
          <div class="compare">
            较昨日
            <span :class="statistics.salesIncrease >= 0 ? 'up' : 'down'">
              {{ Math.abs(statistics.salesIncrease) }}%
              <el-icon>
                <component :is="statistics.salesIncrease >= 0 ? 'CaretTop' : 'CaretBottom'" />
              </el-icon>
            </span>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="data-card">
          <div class="card-header">
            <div class="title">运行设备</div>
            <el-icon class="icon"><Monitor /></el-icon>
          </div>
          <div class="number">{{ statistics.runningMachineCount }}</div>
          <div class="compare">
            占比
            <span class="normal">{{ statistics.machineRunningRate }}%</span>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="data-card">
          <div class="card-header">
            <div class="title">待处理工单</div>
            <el-icon class="icon"><Document /></el-icon>
          </div>
          <div class="number">{{ statistics.pendingWorkOrderCount }}</div>
          <div class="compare">
            较昨日
            <span :class="statistics.workOrderIncrease >= 0 ? 'up' : 'down'">
              {{ Math.abs(statistics.workOrderIncrease) }}%
              <el-icon>
                <component :is="statistics.workOrderIncrease >= 0 ? 'CaretTop' : 'CaretBottom'" />
              </el-icon>
            </span>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 图表区域 -->
    <el-row :gutter="20" class="chart-row">
      <el-col :span="16">
        <el-card class="chart-card" v-loading="loading.salesTrend">
          <template #header>
            <div class="chart-header">
              <span>销售趋势</span>
              <el-radio-group v-model="salesChartType" size="small">
                <el-radio-button label="week">本周</el-radio-button>
                <el-radio-button label="month">本月</el-radio-button>
              </el-radio-group>
            </div>
          </template>
          <div class="chart-container">
            <v-chart :option="salesChartOption" autoresize />
          </div>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card class="chart-card" v-loading="loading.productRank">
          <template #header>
            <div class="chart-header">
              <span>商品销量排行</span>
            </div>
          </template>
          <div class="chart-container">
            <v-chart :option="productRankChartOption" autoresize />
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 区域数据表格 -->
    <el-card class="table-card" v-loading="loading.areaData">
      <template #header>
        <div class="table-header">
          <span>区域运营数据</span>
          <el-button type="primary" link @click="exportAreaData">导出数据</el-button>
        </div>
      </template>
      <el-table :data="areaData" border style="width: 100%">
        <el-table-column prop="areaName" label="区域" />
        <el-table-column prop="machineCount" label="设备数量" align="center" />
        <el-table-column prop="orderCount" label="订单数" align="center" />
        <el-table-column prop="sales" label="销售额" align="center">
          <template #default="{ row }">
            ¥{{ row.sales.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="runningRate" label="设备运行率" align="center">
          <template #default="{ row }">
            <el-progress
              :percentage="row.runningRate"
              :color="getProgressColor(row.runningRate)"
            />
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted, watch } from 'vue'
import { use } from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'
import { LineChart, BarChart } from 'echarts/charts'
import {
  GridComponent,
  TooltipComponent,
  LegendComponent,
  TitleComponent
} from 'echarts/components'
import VChart from 'vue-echarts'
import { ShoppingCart, Money, Monitor, Document, CaretTop, CaretBottom, Moon, Sunny, Refresh } from '@element-plus/icons-vue'
import { 
  getStatistics, 
  getSalesTrend, 
  getProductRank, 
  getAreaData,
  exportAreaData as exportAreaDataApi
} from '@/api/dashboard'
import { ElMessage } from 'element-plus'

// 注册 ECharts 组件
use([
  CanvasRenderer,
  LineChart,
  BarChart,
  GridComponent,
  TooltipComponent,
  LegendComponent,
  TitleComponent
])

// 统计数据
const statistics = ref({
  todayOrderCount: 0,
  orderIncrease: 0,
  todaySales: 0,
  salesIncrease: 0,
  runningMachineCount: 0,
  machineRunningRate: 0,
  pendingWorkOrderCount: 0,
  workOrderIncrease: 0
})

// 销售趋势图表类型
const salesChartType = ref('week')

// 销售趋势图表配置
const salesChartOption = ref({
  tooltip: {
    trigger: 'axis'
  },
  legend: {
    data: ['订单数', '销售额']
  },
  xAxis: {
    type: 'category',
    data: []
  },
  yAxis: [
    {
      type: 'value',
      name: '订单数',
      position: 'left'
    },
    {
      type: 'value',
      name: '销售额',
      position: 'right',
      axisLabel: {
        formatter: '¥{value}'
      }
    }
  ],
  series: [
    {
      name: '订单数',
      type: 'line',
      data: []
    },
    {
      name: '销售额',
      type: 'line',
      yAxisIndex: 1,
      data: []
    }
  ]
})

// 商品销量排行图表配置
const productRankChartOption = ref({
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'shadow'
    }
  },
  xAxis: {
    type: 'value'
  },
  yAxis: {
    type: 'category',
    data: []
  },
  series: [
    {
      type: 'bar',
      data: []
    }
  ]
})

// 区域数据
const areaData = ref([])

// 加载状态
const loading = reactive({
  statistics: false,
  salesTrend: false,
  productRank: false,
  areaData: false
})

// 主题切换
const darkMode = ref(false)

// 图表主题配置
const darkTheme = {
  backgroundColor: '#1e1e1e',
  textColor: '#ffffff',
  axisLineColor: '#484848',
  splitLineColor: '#484848',
  legendTextColor: '#cccccc'
}

const lightTheme = {
  backgroundColor: '#ffffff',
  textColor: '#333333',
  axisLineColor: '#e0e0e0',
  splitLineColor: '#e0e0e0',
  legendTextColor: '#666666'
}

// 更新图表主题
const updateChartTheme = (theme) => {
  const commonConfig = {
    backgroundColor: theme.backgroundColor,
    textStyle: {
      color: theme.textColor
    },
    legend: {
      textStyle: {
        color: theme.legendTextColor
      }
    },
    xAxis: {
      axisLine: {
        lineStyle: {
          color: theme.axisLineColor
        }
      },
      splitLine: {
        lineStyle: {
          color: theme.splitLineColor
        }
      }
    },
    yAxis: {
      axisLine: {
        lineStyle: {
          color: theme.axisLineColor
        }
      },
      splitLine: {
        lineStyle: {
          color: theme.splitLineColor
        }
      }
    }
  }

  salesChartOption.value = {
    ...salesChartOption.value,
    ...commonConfig
  }

  productRankChartOption.value = {
    ...productRankChartOption.value,
    ...commonConfig
  }
}

// 主题切换处理
const handleThemeChange = (value) => {
  updateChartTheme(value ? darkTheme : lightTheme)
}

// 获取进度条颜色
const getProgressColor = (value) => {
  if (value >= 90) return '#67C23A'
  if (value >= 70) return '#E6A23C'
  return '#F56C6C'
}

// 导出区域数据
const exportAreaData = async () => {
  try {
    const response = await exportAreaDataApi()
    const blob = new Blob([response.data])
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = '区域运营数据.xlsx'
    link.click()
    window.URL.revokeObjectURL(url)
  } catch (error) {
    console.error('导出数据失败:', error)
    ElMessage.error('导出失败')
  }
}

// 获取统计数据
const getStatisticsData = async () => {
  loading.statistics = true
  try {
    const { data } = await getStatistics()
    statistics.value = data
  } catch (error) {
    console.error('获取统计数据失败:', error)
  } finally {
    loading.statistics = false
  }
}

// 获取销售趋势数据
const getSalesTrendData = async () => {
  loading.salesTrend = true
  try {
    const { data } = await getSalesTrend(salesChartType.value)
    salesChartOption.value.xAxis.data = data.dates
    salesChartOption.value.series[0].data = data.orderCounts
    salesChartOption.value.series[1].data = data.salesAmounts
  } catch (error) {
    console.error('获取销售趋势数据失败:', error)
  } finally {
    loading.salesTrend = false
  }
}

// 获取商品销量排行
const getProductRankData = async () => {
  loading.productRank = true
  try {
    const { data } = await getProductRank()
    productRankChartOption.value.yAxis.data = data.map(item => item.name)
    productRankChartOption.value.series[0].data = data.map(item => item.count)
  } catch (error) {
    console.error('获取商品销量排行失败:', error)
  } finally {
    loading.productRank = false
  }
}

// 获取区域数据
const getAreaDataList = async () => {
  loading.areaData = true
  try {
    const { data } = await getAreaData()
    areaData.value = data
  } catch (error) {
    console.error('获取区域数据失败:', error)
  } finally {
    loading.areaData = false
  }
}

// 监听销售趋势图表类型变化
watch(salesChartType, () => {
  getSalesTrendData()
})

// 刷新状态
const refreshing = ref(false)

// 刷新按钮点击处理
const handleRefresh = async () => {
  if (refreshing.value) return
  
  refreshing.value = true
  try {
    await Promise.all([
      getStatisticsData(),
      getSalesTrendData(),
      getProductRankData(),
      getAreaDataList()
    ])
    ElMessage.success('数据刷新成功')
  } catch (error) {
    console.error('刷新数据失败:', error)
    ElMessage.error('数据刷新失败')
  } finally {
    refreshing.value = false
  }
}

// 定时刷新数据
let refreshTimer = null

onMounted(() => {
  // 初始化图表主题
  updateChartTheme(lightTheme)
  
  // 获取数据
  getStatisticsData()
  getSalesTrendData()
  getProductRankData()
  getAreaDataList()

  // 每5分钟刷新一次数据
  refreshTimer = setInterval(() => {
    getStatisticsData()
    getSalesTrendData()
    getProductRankData()
    getAreaDataList()
  }, 5 * 60 * 1000)
})

onUnmounted(() => {
  if (refreshTimer) {
    clearInterval(refreshTimer)
  }
})
</script>

<style scoped>
.dashboard-container {
  padding: 20px;
}

.data-card {
  height: 180px;
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.title {
  font-size: 16px;
  color: #606266;
}

.icon {
  font-size: 24px;
  color: #409eff;
}

.number {
  font-size: 36px;
  font-weight: bold;
  margin-bottom: 10px;
}

.compare {
  color: #909399;
  font-size: 14px;
}

.up {
  color: #67c23a;
}

.down {
  color: #f56c6c;
}

.normal {
  color: #409eff;
}

.chart-row {
  margin-top: 20px;
}

.chart-card {
  height: 400px;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chart-container {
  height: 320px;
}

.table-card {
  margin-top: 20px;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.toolbar {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 20px;
  gap: 16px;
}

.theme-switch {
  margin-left: 16px;
}

/* 暗色主题样式 */
.dashboard-container.dark-mode {
  background-color: #141414;
}

.dark-mode .el-card {
  background-color: #1e1e1e;
  color: #ffffff;
  border-color: #484848;
}

.dark-mode .title {
  color: #cccccc;
}

.dark-mode .compare {
  color: #a0a0a0;
}

.dark-mode .el-table {
  background-color: #1e1e1e;
  color: #ffffff;
}

.dark-mode .el-table th,
.dark-mode .el-table td {
  background-color: #1e1e1e;
  border-color: #484848;
}

.dark-mode .el-table--border {
  border-color: #484848;
}

.dark-mode .chart-container {
  background-color: #1e1e1e;
}
</style> 